<template>
  <div class="app-container">
    <el-form
      ref="formRef"
      :disabled="!editAble"
      :model="form"
      :rules="rules"
      label-width="110px"
      class="form-search"
    >
      <el-button
        v-if="!form.id"
        v-hasPermi="['tech:recipe:query']"
        :disabled="!!form.id"
        type="primary"
        icon="plus"
        @click="handlePicker"
      >
        选择产品
      </el-button>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="产品编号" prop="prodNo">
            <div class="form-text">{{ form.prodNo }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产品名称" prop="prodName">
            <div class="form-text">{{ form.prodName }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产品分类" prop="prodTypeName">
            <div class="form-text">{{ form.prodTypeName }}</div>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="工厂" prop="factoryName">
            <div class="form-text">{{ form.factoryName }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标准生产数量" prop="standardProdCount">
            <el-input-number
              v-if="editAble"
              v-model="form.standardProdCount"
              placeholder="请输入标准生产数量"
              :min="0"
              step-strictly
              controls-position="right"
              clearable
            ></el-input-number>
            <div v-else class="form-text">{{ form.standardProdCount }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单位" prop="unit">
            <div class="form-text">{{ form.unit }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="规格" prop="packages">
            <div class="form-text">{{ form.packages }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="型号" prop="model">
            <div class="form-text">{{ form.model }}</div>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="版本号" prop="version">
            <div class="form-text">{{ form.version }}</div>
          </el-form-item>
        </el-col>
        <el-col v-if="!editAble" :span="6">
          <el-form-item label="状态" prop="status">
            <dict-tag :options="tech_recipe_status" :value="form.status" />
            <!-- <div class="form-text">{{ form.status }}</div> -->
          </el-form-item>
        </el-col>
        <el-col v-if="!editAble" :span="6">
          <el-form-item label="创建时间" prop="createTime">
            <div class="form-text">{{ form.createTime }}</div>
          </el-form-item>
        </el-col>
        <el-col v-if="!editAble" :span="6">
          <el-form-item label="修改时间" prop="updateTime">
            <div class="form-text">{{ form.updateTime }}</div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="物料明细" name="first">
        <el-row v-if="editAble" :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="plus" @click="handleAddWhStorehouseInDetail">
              选择物料
            </el-button>
          </el-col>
        </el-row>
        <el-form ref="tableForm" :model="recipeMaterialList" label-width="0">
          <el-table
            :data="recipeMaterialList"
            :header-cell-class-name="start"
            maxHeight="400"
            border
            v-loading="loading"
            :row-class-name="rowWhStorehouseInDetailIndex"
            ref="whStorehouseInDetail"
          >
            <!--            <el-table-column
              label="序号"
              align="center"
              prop="index"
              width="50"
            />-->
            <el-table-column label="物料编号" prop="code" />
            <el-table-column label="物料名称" prop="name" />
            <el-table-column label="物料分类" prop="typeName" />
            <el-table-column label="单位" prop="measureUnit" />

            <el-table-column label="规格" prop="packages" />
            <el-table-column
              label="型号"
              align="center"
              prop="model"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="品牌"
              align="center"
              prop="brand"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="数量" prop="num">
              <template v-if="editAble" #default="scope">
                <el-form-item
                  label=""
                  :prop="`[${scope.$index}].num`"
                  :rules="[
                    {
                      required: true,
                      message: '请输入数量',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-input-number
                    v-model="scope.row.num"
                    controls-position="right"
                  ></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="损耗系数" prop="lossCoefficient">
              <template v-if="editAble" #default="scope">
                <el-form-item
                  label=""
                  :prop="`[${scope.$index}].lossCoefficient`"
                  :rules="[
                    {
                      required: true,
                      message: '请输入损耗系数',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-input-number
                    v-model="scope.row.lossCoefficient"
                    controls-position="right"
                    :min="0"
                    :precision="3"
                  ></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              v-if="editAble"
              label="操作"
              align="center"
              fixed="right"
              minWidth="100"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  v-hasPermi="['tech:recipeDetail:remove']"
                  @click="handleDeleteWhStorehouseInDetail(scope.row, scope.$index)"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getProdMatList"
          />
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <matDialog v-model:show="show" :data="recipeMaterialList" @change="handleChange"></matDialog>
    <DialogTable
      title="选择产品"
      v-model:show="showProd"
      :initParam="initParam"
      :api="requestApi"
      :multiple="false"
      rowKey="code"
      labelKey="name"
      :columns="columns"
      :search="searchParams"
      :dataCallback="dataCallback"
      :showPagination="true"
      @change="selectProd"
    ></DialogTable>
  </div>
</template>

<script setup name="warehouse">
// import {
//   listWhStorehouseInDetail,
// } from "@/api/warehouse/WhStorehouseInDetail";
import {
  listRecipe,
  getRecipe,
  addRecipe,
  updateRecipe,
  recipeMatList,
  delRecipeMat,
  matFeignSelect,
} from "@/api/technology/formulation";
import DialogTable from "@/components/DialogTable";

import { ref, reactive, toRefs, useAttrs, getCurrentInstance, onMounted } from "vue";
import matDialog from "./components/matDialog.vue";
import { PRODUCT, SF_PRODUCT } from "@/constant";
const attrs = useAttrs();
const { proxy } = getCurrentInstance();
const activeName = ref("first");
// const { inout_storehouse } = proxy.useDict("inout_storehouse");
const operationTitle = ref("");
const { tech_recipe_status } = proxy.useDict("tech_recipe_status");
const showProd = ref(false);
const loading = ref(false);
const total = ref(0);
const formulaId = ref();
const initParam = ref({
  type: `${PRODUCT},${SF_PRODUCT}`,
});
const requestApi = ref(matFeignSelect);
const refData = reactive({
  // 表单参数
  form: {},
  // 表单校验
  rules: {
    recipeGroupCounter: [{ required: true, message: "请输入产品组计数器!", trigger: "blur" }],
    standardProdCount: [
      {
        required: true,
        message: "请输入标准生产数量!",
        type: "number",
        trigger: "blur",
      },
    ],
    sampleCount: [
      {
        required: true,
        message: "请输入取样量!",
        type: "number",
        trigger: "blur",
      },
    ],
    num: [
      {
        required: true,
        message: "请输入数量!",
        type: "number",
        trigger: ["change", "blur"],
      },
    ],
  },
  columns: [
    {
      label: "产品编号",
      align: "center",
      prop: "code",
    },
    {
      label: "产品名称",
      align: "center",
      prop: "name",
    },
    {
      label: "产品分类",
      align: "center",
      prop: "typeName",
    },
    {
      label: "工厂",
      align: "center",
      prop: "factoryName",
    },
    {
      label: "单位",
      align: "center",
      prop: "measureUnit",
    },
    {
      label: "规格",
      align: "center",
      prop: "packages",
    },
    {
      label: "型号",
      align: "center",
      prop: "model",
    },
    {
      label: "品牌",
      align: "center",
      prop: "brand",
    },
  ],
  searchParams: [
    {
      label: "工厂",
      prop: "factory",
    },
    {
      label: "产品编号",
      prop: "code",
    },
    {
      label: "产品名称",
      prop: "name",
    },
  ],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
  },
});
const { form, rules, searchParams, queryParams, columns } = toRefs(refData);
const emit = defineEmits(["close", "setActions", "setIsActionTop"]);
const recipeMaterialList = ref([]);
const formRef = ref("formRef");
const tableForm = ref("tableForm");
const show = ref(false);
const editAble = ref(false);
const binEditAble = ref(false);
const start = ({ columnIndex }) => {
  if (columnIndex == 7 || columnIndex == 8) {
    return "start";
  }
};
const actions = ref([
  {
    text: "取 消",
    theme: "",
    hasPermi: ["tech:recipeDetail:add"],
    handle: () => {
      cancel();
    },
  },
  {
    text: "确 定",
    theme: "primary",
    handle: () => {
      submitForm();
    },
    loading: false,
  },
]);

const handlePicker = () => {
  showProd.value = true;
};

const dataCallback = (res) => {
  return res.rows || [];
};

const selectProd = (data) => {
  form.value.prodNo = data.code;
  form.value.prodName = data.name;
  form.value.prodTypeName = data.typeName;
  form.value.prodType = data.type;
  form.value.factoryName = data.factoryName;
  form.value.factoryCode = data.factory;
  // form.value.standardProdCount = 0
  form.value.unit = data.measureUnit;
  form.value.packages = data.packages;
  form.value.model = data.model;
  form.value.brand = data.brand;
  form.value.version = "v1.0";
  getProdList(data.code, "add");
};

// 取消按钮
function cancel() {
  emit("close");
}
// 表单重置
function reset() {
  form.value = {
    prodTypeName: "",
    factoryName: "",
    prodName: "",
    prodNo: "",
    standardProdCount: 0,
    packages: "",
    model: "",
    unit: "",
  };
  formRef.value.resetFields();
  recipeMaterialList.value = [];
}

/** 修改按钮操作 */
function getDetail(code) {
  getRecipe({ recipeCode: code }).then((response) => {
    form.value = response.data;
    getProdMatList();
  });
}

function getProdList(code, type) {
  listRecipe({
    prodNo: code,
  }).then((res) => {
    if (type === "add" && res.rows && res.rows.length) {
      proxy.$modal.msgError("该产品已有记录，无法新增！");
      reset();
      return;
    }
    recipeMaterialList.value = res.rows;
  });
}

function getProdMatList(type) {
  loading.value = true;
  recipeMatList({
    recipeId: formulaId.value,
    ...queryParams.value,
  }).then((res) => {
    if (type === "add" && res.rows && res.rows.length) {
      proxy.$modal.msgError("该产品已有记录，无法新增！");
      reset();
      return;
    }
    total.value = res.total;
    loading.value = false;
    recipeMaterialList.value = res.rows;
  });
}

/** 提交按钮 */
function submitForm() {
  if (!form.value.prodNo) {
    proxy.$modal.msgError("请选择产品");
    return;
  }
  formRef.value.validate((valid) => {
    if (valid) {
      form.value.recipeMaterialList = recipeMaterialList.value;
      if (recipeMaterialList.value.length) {
        tableForm.value.validate((result) => {
          if (result) {
            submitData();
          }
        });
        return;
      }
      submitData();
    }
  });
}

function submitData() {
  if (form.value.id) {
    updateRecipe(form.value).then(() => {
      proxy.$modal.msgSuccess("编辑成功");
      cancel();
    });
  } else {
    addRecipe(form.value).then(() => {
      proxy.$modal.msgSuccess("新增成功");
      cancel();
      // addRecipeMat().then(){

      // }
    });
  }
}

/** 物料入仓明细序号 */
function rowWhStorehouseInDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}
/** 物料入仓明细添加按钮操作 */
function handleAddWhStorehouseInDetail() {
  if (!form.value.prodNo) {
    proxy.$modal.msgError("请选择产品");
    return;
  }
  show.value = true;
}
function handleChange(val) {
  if (val.length) {
    const recipeMaterialCodes = recipeMaterialList.value.map((item) => item.code);
    val.forEach((el) => {
      if (!recipeMaterialCodes.includes(el.code)) {
        recipeMaterialList.value.push({
          code: el.code,
          measureUnit: el.measureUnit,
          packages: el.packages,
          name: el.name,
          num: el.num || 0,
          brand: el.brand,
          model: el.model,
          type: el.type,
          typeName: el.typeName,
          prodNo: form.value.prodNo,
        });
      }
    });
  }
}
/** 物料入仓明细删除按钮操作 */
function handleDeleteWhStorehouseInDetail(row, index) {
  const msg = `是否确认移除物料编号为${row.code}的数据项？`;
  proxy.$modal
    .confirm(msg)
    .then(() => {
      if (row.id) {
        delRecipeMat({ id: row.id }).then(() => {
          recipeMaterialList.value.splice(index, 1);
          proxy.$modal.msgSuccess("删除成功");
        });
      } else {
        recipeMaterialList.value.splice(index, 1);
        proxy.$modal.msgSuccess("删除成功");
      }
    })
    .catch(() => {});
}

// function getListWhStorehouseInDetail(code) {
//   listWhStorehouseInDetail({ storehouseInCode: code }).then((res) => {
//     recipeMaterialList.value = res.rows;
//   });
// }

onMounted(() => {
  reset();
  const { data, title } = attrs;
  binEditAble.value = true;
  operationTitle.value = title;
  if (title === "查看产品详情") {
    editAble.value = false;
    actions.value = [];
  } else {
    editAble.value = true;
    actions.value = [
      {
        text: "取 消",
        theme: "",
        handle: () => {
          cancel();
        },
      },
      {
        text: "确 定",
        theme: "primary",
        handle: () => {
          submitForm();
        },
        loading: false,
      },
    ];
  }
  emit("setActions", actions.value);

  if (data) {
    formulaId.value = data.id;
    getDetail(data.prodNo, data.id);
  }
});
</script>

<style lang="scss" scoped>
.form-text {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.el-table table tr th.start div::before) {
  color: red;
  content: "*";
}
</style>
